use sea_orm::{Database, DbBackend, Linked, ModelTrait, QueryTrait, RelationDef, RelationTrait};
use crate::entity::{links, menu, user_menu};
use crate::{blog, Column, Entity, Relation, user};


/*
Related 是我们在实体关系图上绘制的箭头（1-1,1-N，M-N）的表示。Linked 链接由一系列关系组成，在以下情况下很有用：
    一对实体之间存在多条连接路径
    在关系查询中跨多个实体连接
举个简单的例子，我们通过一个中间的 user_menu 表将蛋糕和馅料连接起来。
*/
pub struct UserToMenu;

impl Linked for UserToMenu {
    type FromEntity = user::Entity;

    type ToEntity = menu::Entity;

    fn link(&self) -> Vec<RelationDef> {
        vec![
            user_menu::Relation::User.def().rev(),
            user_menu::Relation::Menu.def(),
        ]
    }
}

// 8、通过关系进行关联查询
/*
Linked 链接由一系列关系组成，在以下情况下很有用：
    一对实体之间存在多条连接路径
    在关系查询中跨多个实体连接
*/
async fn user_links() {
    let db = Database::connect("mysql://root:123456@localhost:3306/test").await.unwrap();

    /// 8、通过关系进行关联查询
    /// 参考 sea-orm 官方网站： https://www.sea-ql.org/SeaORM/docs/relation/chained-relations

    // 关联查询，查询用户的博客
    // Lazy Loading
    let user_model = user::Model {
        user_id: String::from("12"),
        name: "".to_owned(),
        ..Default::default()
    };

    assert_eq!(
        user_model
            .find_linked(UserToMenu)
            .build(DbBackend::MySql)
            .to_string(),
        [
            "SELECT `filling`.`id`, `filling`.`name`, `filling`.`vendor_id`",
            "FROM `filling`",
            "INNER JOIN `cake_filling` AS `r0` ON `r0`.`filling_id` = `filling`.`id`",
            "INNER JOIN `cake` AS `r1` ON `r1`.`id` = `r0`.`cake_id`",
            "WHERE `r1`.`id` = 12",
        ]
            .join(" ")
    );

    // Eager Loading
    assert_eq!(
        Entity::find()
            .find_also_linked(links::UserToMenu)
            .build(DbBackend::MySql)
            .to_string(),
        [
            r#"SELECT `cake`.`id` AS `A_id`, `cake`.`name` AS `A_name`,"#,
            r#"`r1`.`id` AS `B_id`, `r1`.`name` AS `B_name`, `r1`.`vendor_id` AS `B_vendor_id`"#,
            r#"FROM `cake`"#,
            r#"LEFT JOIN `cake_filling` AS `r0` ON `cake`.`id` = `r0`.`cake_id`"#,
            r#"LEFT JOIN `filling` AS `r1` ON `r0`.`filling_id` = `r1`.`id`"#,
        ]
            .join(" ")
    );

}